﻿namespace CNVP.Framework.URLRewriter
{
    using CNVP.Framework.URLRewriter.Config;
    using System;
    using System.Text.RegularExpressions;
    using System.Web;

    public class ModuleRewriter : BaseModuleRewriter
    {
        protected override void Rewrite(string requestedPath, HttpApplication app)
        {
            string sendToUrl = string.Empty;
            app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
            for (int i = 0; i < rules.Count; i++)
            {
                Regex regex = new Regex("^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$", RegexOptions.IgnoreCase);
                //二级域名重定向"
                //Regex regex = new Regex("^" + rules[i].LookFor + "$", RegexOptions.IgnoreCase);
                if (regex.IsMatch(requestedPath))
                {
                    //string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, regex.Replace(requestedPath, rules[i].SendTo));
                    sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, regex.Replace(requestedPath, rules[i].SendTo));
                    app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);

                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                    break;
                }
            }
            if (!string.IsNullOrEmpty(sendToUrl))
            {
                requestedPath = sendToUrl;
            }
            app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");
        }
    }
}